let api = require('../../../api/api.js')
const app = getApp()
Page({
  /**
   * 页面的初始数据
   */
  data: {
    length: false,
    carts: [],               // 购物车列表
    hasList: false,          // 列表是否有数据
    totalPrice: 0,           // 总价，初始为0
    selectAllStatus: true,    // 全选状态，默认全选
    startX: 0, //开始坐标
    startY: 0,
    tokenState: false,
  },
  url: function () {
    wx.navigateTo({
      url: '../../xiangqing/xiangqing',
    })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    // this.setData({
    //   hasList: true,        // 既然有数据了，那设为true吧
    //   carts: [
    //   ]
    // });
        
  },
  stateShoppingS(id,num){ //  添加减少
    let data = {
      sc_id:id,
      num:num
    }
    api.stateShopping(data,(res)=>{
      console.log(res)
    })
  },
  goPlay(){
    let carts = this.data.carts; 
    let cartsData = [];
    carts.forEach((item)=>{
      console.log(item)
      if (item.selected == true){
        cartsData.push({
          num: item.num,
          sc_id: item.sc_id,
          type: 2
        })
        let datas = JSON.stringify(cartsData)
        wx.setStorageSync('datas', datas)
        console.log(datas)
        wx.navigateTo({
          url: `/pages/buy/create/create`,
        })
        // wx.setStorageSync('datas', datas)
      }
      
    })

    
  },
  selectList(e) {
    const index = e.currentTarget.dataset.index;    // 获取data- 传进来的index
    let carts = this.data.carts;                    // 获取购物车列表
    const selected = carts[index].selected;         // 获取当前商品的选中状态
    carts[index].selected = !selected;              // 改变状态
    this.setData({
      carts: carts
    });
    if (carts[index].selected == false) {
      this.setData({
        selectAllStatus: false
      })
    }
    this.getTotalPrice();                           // 重新获取总价
  },

  selectAll(e) {
    let selectAllStatus = this.data.selectAllStatus;    // 是否全选状态
    selectAllStatus = !selectAllStatus;
    let carts = this.data.carts;

    for (let i = 0; i < carts.length; i++) {
      carts[i].selected = selectAllStatus;            // 改变所有商品状态
    }
    this.setData({
      selectAllStatus: selectAllStatus,
      carts: carts
    });
    this.getTotalPrice();                               // 重新获取总价
  },
  //加
  addCount(e) {
    const index = e.currentTarget.dataset.index;
    let carts = this.data.carts;
    let id = e.currentTarget.id
    let num = carts[index].num;
    num =  ++num;
    carts[index].num = num;
    this.setData({
      carts: carts
    });

    this.getTotalPrice();
    this.stateShoppingS(id, num)
  },

  // 减少数量
  minusCount(e) {
    const index = e.currentTarget.dataset.index;
    let carts = this.data.carts;
    let id = e.currentTarget.id
    let num = carts[index].num;
    if (num <= 1) {
      return false;
    }
    num = num - 1;
    carts[index].num = num;
    this.setData({
      carts: carts
    });
    this.getTotalPrice();
    this.stateShoppingS(id, num)

  },
  //删除
  deleteList(e) {
    const index = e.currentTarget.dataset.index;
    let id = e.currentTarget.id
    let carts = this.data.carts;
    carts.splice(index, 1);              // 删除购物车列表里这个商品
    this.setData({
      carts: carts
    });
    let data ={
      sc_id:id
    }
    api.removeShopping(data,(res)=>{
      console.log(res)
    })  
    if (!carts.length) {                  // 如果购物车为空
      this.setData({
        hasList: false,             // 修改标识为false，显示购物车为空页面
        selectAllStatus:false
      });
      this.getTotalPrice();  
    } else {                      // 如果不为空
      this.getTotalPrice();           // 重新计算总价格
    }
  },
  // 计算价格
  getTotalPrice() {
    let carts = this.data.carts;                  // 获取购物车列表
    console.log(carts)
    let total = 0;
    for (let i = 0; i < carts.length; i++) {         // 循环列表得到每个数据
      if (carts[i].selected) {                   // 判断选中才会计算价格
        total += carts[i].num * carts[i].price;     // 所有价格加起来
      }
    }
    this.setData({                                // 最后赋值到data中渲染到页面
      carts: carts,
      totalPrice: total.toFixed(2)
    });
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },
  touchstart: function (e) {
    //开始触摸时 重置所有删除
    this.data.carts.forEach(function (v, i) {
      if (v.isTouchMove)//只操作为true的
        v.isTouchMove = false;
    })
    this.setData({
      startX: e.changedTouches[0].clientX,
      startY: e.changedTouches[0].clientY,
      carts: this.data.carts
    })
  },
  //滑动事件处理
  touchmove: function (e) {
    var that = this,
      index = e.currentTarget.dataset.index,//当前索引
      startX = that.data.startX,//开始X坐标
      startY = that.data.startY,//开始Y坐标
      touchMoveX = e.changedTouches[0].clientX,//滑动变化坐标
      touchMoveY = e.changedTouches[0].clientY,//滑动变化坐标
      //获取滑动角度
      angle = that.angle({ X: startX, Y: startY }, { X: touchMoveX, Y: touchMoveY });

    that.data.carts.forEach(function (v, i) {
      v.isTouchMove = false
      //滑动超过30度角 return
      if (Math.abs(angle) > 30) return;
      if (i == index) {
        if (i == index) {
          if (touchMoveX > startX) {
            v.isTouchMove = false
            console.log('右滑')
          } else {
            v.isTouchMove = true
          }
        }

      }
    })
    //更新数据
    that.setData({
      carts: that.data.carts
    })
  },
  /**
   * 计算滑动角度
   * @param {Object} start 起点坐标
   * @param {Object} end 终点坐标
   */
  angle: function (start, end) {
    var _X = end.X - start.X,
      _Y = end.Y - start.Y
    //返回角度 /Math.atan()返回数字的反正切值
    return 360 * Math.atan(_Y / _X) / (2 * Math.PI);
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    this.shoppingList()
    let token = wx.getStorageSync("token")
    let that = this
    
    if (token) {
      this.setData({
        tokenState: false,
        selectAllStatus: true,
        totalPrice:0
      })
    } else {
      this.setData({
        tokenState: true
      })
    }
    this.getTotalPrice();
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },
  
  shoppingList:function(){
    var that = this;
    api.shoppingList( (res) =>{
      // console.log(res)
      if (res.data.description == 50002){
        that.setData({
          tokenState:true
        })
      }else{
        var carts = res.data.result
        var selectAllStatus = that.data.selectAllStatus
        if(carts.length == 0){
          selectAllStatus = false
        }else{
          carts.forEach(function (element) {
            element.selected = that.data.selectAllStatus
          })
          selectAllStatus = true
        }
        
        this.setData({
          carts: carts,
          selectAllStatus: selectAllStatus
        })
      }
      this.getTotalPrice();
    })
  }, 
  shopContent:function(e){
    var s_id = e.currentTarget.id;
    var id = e.currentTarget.dataset.cateid
    
    wx.navigateTo({
      url: '/pages/buy/buyConten/buyConten?id=' + id + '&type=1&s_id=' + s_id 
    })
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }, // 授权
  onGotUserInfo: function (e) {
    var S = this;
    wx.getUserInfo({
      success: function (res) {
        console.log(res)
        let userInfo = e.detail.userInfo
        let data = {
          user_name: e.detail.userInfo.nickName,
          user_img: e.detail.userInfo.avatarUrl,
          openid_wechat: wx.getStorageSync("key").openid,
          level: app.globalData.level
        }
        api.tokens(data, (res) => {
          console.log(res)
          wx.setStorageSync('token', res.data.result)
          console.log(res.data.result)
          S.setData({
            tokenState: false
          })
          S.shoppingList()
          
        })
      },
      fail: function (err) {
        wx.showToast({
          title: '授权失败',
          icon: 'none',
          duration: 2000
        })
      }
    })
  }
})